package com.intellif.mozping.lockp.rwl;

import com.intellif.mozping.tools.SleepTools;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author by mozping
 * @Classname SimulateDbAccess
 * @Description 模拟数据库的访问，有2个写入的线程和10个读取的线程
 * @Date 2019/1/2 20:20
 */
public class SimulateDbAccess {

    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.writeLock();

    public static void main(String[] args) {

        for (int i = 0; i < 3; i++) {
            new MyReadDbThread().start();
        }

        for (int i = 0; i < 1; i++) {
            new MyWriteDbThread().start();
        }
    }

    private static class MyReadDbThread extends Thread {
        @Override
        public void run() {
            for (; ; ) {
                try {
                    readLock.lock();
                    System.out.println("[" + Thread.currentThread().getName() + "]读取线程读取数据库开始...");
                    SleepTools.ms(3000);
                    System.out.println("[" + Thread.currentThread().getName() + "]读取线程读取数据库结束...");
                } catch (Exception e) {

                } finally {
                    readLock.unlock();
                }
                //休眠片刻
                SleepTools.ms(2000);
            }
        }
    }

    private static class MyWriteDbThread extends Thread {
        @Override
        public void run() {
            for (; ; ) {
                try {
                    writeLock.lock();
                    System.out.println("[" + Thread.currentThread().getName() + "]写入线程写入数据库开始...");
                    SleepTools.ms(5000);
                    System.out.println("[" + Thread.currentThread().getName() + "]写入线程写入数据库结束...");
                } catch (Exception e) {

                } finally {
                    writeLock.unlock();
                }
                //休眠片刻
                SleepTools.ms(3000);
            }
        }
    }
}
